//
//  HBSearchController.m
//  HeartBeat
//
//  Created by karong on 2023/8/24.
//

#import "HBSearchController.h"
#import "HBSearchResultController.h"
#import "HBSearchHistoryCell.h"
#import "HBEqualSpaceFlowLayoutEvolve.h"
#import "HBSearchFooterView.h"

@interface HBSearchController () <UITextFieldDelegate, HBSearchFooterViewDelegate, HBSearchResultControllerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *tf;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *listViewTop;
@property (strong ,nonatomic) HBEqualSpaceFlowLayoutEvolve *flowLayout;
@property (strong, nonatomic) NSMutableArray * historyArray;
@property (nonatomic, strong) NSArray * dataArray;
@property (nonatomic, strong) HBSearchResultController * searchResultVC;
@end

@implementation HBSearchController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.bg_gray_f2f2f2;
    [self layoutListViewTop];
    self.flowLayout = [[HBEqualSpaceFlowLayoutEvolve alloc]initWthType:HBAlignWithLeft];
    self.flowLayout.betweenOfCell = 12;
    self.flowLayout.inset = 12;
    self.flowLayout.minimumLineSpacing = 12;
    self.listView.collectionViewLayout = self.flowLayout;
    self.tf.tintColor = UIColor.font_yellow_FFCC00;
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:WSLocalized(@"請輸入搜索內容")attributes:@{NSForegroundColorAttributeName:[UIColor colorFromHexRGB:@"CECECE"],NSFontAttributeName:self.tf.font}];
    self.tf.attributedPlaceholder = attrString;
    [self loadSearchHotListsearchResultVCRequest];
}

- (void)showsearchResultVCResultView {
    self.listView.scrollEnabled = NO;
    [self.listView setContentOffset:self.listView.contentOffset animated:NO];
    if (![self.view.subviews containsObject:self.searchResultVC.view]) {
        [self.view addSubview:self.searchResultVC.view];
        [self.searchResultVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.searchView.mas_bottom);
            make.left.right.bottom.mas_equalTo(self.view);
        }];
    }
    [self.searchResultVC searchWithKeyWord:self.tf.text];
}

- (void)layoutListViewTop {
    if (self.historyArray.count > 0) {
        self.listViewTop.constant = 56;
    }
    else {
        self.listViewTop.constant = 0;
    }
    [self.view uploadLayout];
}

- (void)removesearchResultVCResultView {
    self.listView.scrollEnabled = YES;
    [self.searchResultVC.view removeFromSuperview];
    
}

- (void)showNovelDetailWithNovel:(id)novel {
    [ViewManager pushNovelDetailVCWithNovel:novel inController:self];
}

#pragma mark Result
- (void)loadSearchHotListsearchResultVCRequest {
    [HBRequest loadHotSearchSuccess:^(NSArray *array) {
        self.dataArray = array;
        [self.listView reloadData];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (IBAction)searchBtnAction:(id)sender {
    if (KIsNullOrEmpty(self.tf.text)) {
        //返回默認頁面
        [self removesearchResultVCResultView];
    }
    else {
        //搜索
        [self.view endEditing:YES];
        [self showsearchResultVCResultView];
    }
}

- (void)backAction:(id)sender {
    if ([self.view.subviews containsObject:self.searchResultVC.view]) {
        self.tf.text = @"";
        [self removesearchResultVCResultView];
    }
    else if(self.navigationController) {
        if (self.navigationController.viewControllers.firstObject == self) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)clearHistoryAction:(id)sender {
    [self.historyArray removeAllObjects];
    [self layoutListViewTop];
    [appUserDefaults setValue:self.historyArray forKey:@"searchResultVChistory"];
    [self.listView reloadData];
    
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (KIsNullOrEmpty(textField.text)) {
        //返回默認頁面
        [self.searchResultVC.view removeFromSuperview];
    }
    else {
        //搜索
        [textField endEditing:YES];
        [self showsearchResultVCResultView];
    }
    return YES;
}

#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MAX(self.historyArray.count, 1);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBSearchHistoryCell * searchHistoryCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBSearchHistoryCell" forIndexPath:indexPath];
    if (self.historyArray.count > 0) {
        searchHistoryCell.alpha = 1;
        [searchHistoryCell setDataWithObject:self.historyArray[indexPath.row]];
    }
    else {
        searchHistoryCell.alpha = 0;
    }
    return searchHistoryCell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    if (self.historyArray.count > 0) {
        NSString *text = self.historyArray[indexPath.row];
        CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
        size.width = MIN(ceil(textSize.width) + 20, kScreenWidth - 24);
        size.height = 26;
    }
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        HBSearchFooterView * searchFooterView;
        if (!searchFooterView) {
            searchFooterView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HBSearchFooterView" forIndexPath:indexPath];
            searchFooterView.delegate = self;
            [searchFooterView setDataWithObject:self.dataArray];
        }
        return searchFooterView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize size = CGSizeZero;
    size.width = HBScreenWidth;
    if (self.dataArray.count > 0) {
        size.height = 20 + 36 * 5 + 47;
    }
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.tf.text = self.historyArray[indexPath.row];
    [self showsearchResultVCResultView];
}

#pragma mark HBSearchResultControllerDelegate
- (NSArray *)searchResultControllerHotSearchArray {
    return self.dataArray;
}

- (void)searchResultControllerSearchSuccess:(NSString *)keyWord {
    NSInteger index = [self.historyArray indexOfObject:keyWord];
    if (index == NSNotFound) {
        [self.historyArray insertObject:keyWord atIndex:0];
    }
    else {
        [self.historyArray removeObjectAtIndex:index];
        [self.historyArray insertObject:keyWord atIndex:0];
    }
    [self layoutListViewTop];
    [appUserDefaults setValue:self.historyArray forKey:@"searchResultVChistory"];
    [self.listView reloadData];
}

#pragma mark HBSearchFooterViewDelegate
- (void)searchFooterViewActionWithObjct:(HBNovelModel *)object {
    [self showNovelDetailWithNovel:object];
}


- (HBSearchResultController *)searchResultVC {
    if (!_searchResultVC) {
        _searchResultVC = (HBSearchResultController *)[ViewManager searchResultVC];
        _searchResultVC.delegate = self;
        [self addChildViewController:_searchResultVC];
    }
    return _searchResultVC;
}

- (NSMutableArray *)historyArray {
    if (!_historyArray) {
        _historyArray = [[NSMutableArray alloc]initWithArray:[[appUserDefaults arrayForKey:@"searchResultVChistory"] mutableCopy]];
    }
    return _historyArray;
}

@end
